<?php
class LoginForm extends BaseForm {

	public function setup()
	{
		$this->setWidgets(
		array('nombre' => new sfWidgetFormInputText(),
				  'password' => new sfWidgetFormInputPassword(),
			'redirect_to' => new sfWidgetFormInputHidden()
		));

		$this->setValidators(
		array('nombre' => new sfValidatorString(array('max_length' => 255)),
				'password' => new sfValidatorString(array('max_length' => 255)),
				'redirect_to' => new sfValidatorString()));

		$this->widgetSchema->setNameFormat('login[%s]');

		$this->setDefault('redirect_to', sfContext::getInstance()->getRequest()->getUri());
		$this->validatorSchema->setPostValidator(new LoginValidator(array(), array('invalid' => 'Usuario o password inv&aacute;lidos')));

		parent::setup();
	}

	public function autoBind() {
		parent::bind(sfContext::getInstance()->getRequest()->getParameter("login"));
	}
}

class LoginValidator extends sfValidatorBase {

	protected function doClean($values)
	{
		$username = $values['nombre'];
		$password = $values['password'];

		// user exists?
		$user = UsuarioTable::getInstance()->findByNombre($username ? $username : '');
		if ($user)
		{
			if (!$user->getHabilitado()) {
				$this->messages = array('invalid' => 'El usuario esta inhabilitado para ingresar al sistema. Comuniquese con la federacion'); 
				throw new sfValidatorError($this, 'invalid');
			}
			
			// password is ok?
			if ($user->checkPassword($password))
			{
				return array_merge($values, array('usuario' => $user));
			}
		}

		throw new sfValidatorError($this, 'invalid');
	}
}